<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Scheduling tasks for the future</title>
  </head>

  <body>
    <h1>Scheduling tasks for the future</h1>

    <p>现在让我们讨论一下如何让一个任务在N秒之后执行。twisted中提供
    这一功能的方法被定义在 reactor 的接口中 <code
    class="API">twisted.internet.interfaces.IReactorTime</code>:</p>
<pre class="python">
from twisted.internet import reactor

def f(s):
    print "this will run 3.5 seconds after it was scheduled: %s" % s

reactor.callLater(3.5, f, "hello, world")

# f() will only be called if the event loop is started.
reactor.run()
</pre>

    <p>如果说我们要执行的函数（上例中的f()）的返回值很重要，或者这个函数会
    产生一些需要处理的异常，那么我们就需要用到
   <code
    class="API">twisted.internet.task.deferLater</code>，它可以很方便的创建
    并返回一个 <code class="API"
    base="twisted.internet.defer">Deferred</code> 并且为它添加一个delayed 
    call(当延迟运行的函数返回结果时会根据情况调用此函数):</p>
<pre class="python">
from twisted.internet import task
from twisted.internet import reactor

def f(s):
    return "This will run 3.5 seconds after it was scheduled: %s" % s

d = task.deferLater(reactor, 3.5, f, "hello, world")
def called(result):
    print result
d.addCallback(called)

# f() will only be called if the event loop is started.
reactor.run()
</pre>

    <p>如果我们想让一个任务周期性的运行，可以使用
    <code
    class="API">twisted.internet.task.LoopingCall</code>:</p>
<pre class="python">
from twisted.internet import task
from twisted.internet import reactor

def runEverySecond():
    print "a second has passed"

l = task.LoopingCall(runEverySecond)
l.start(1.0) # call every second

# l.stop() will stop the looping calls
reactor.run()
</pre>

    <p>当我们成功添加了一个将要执行的任务之后，又想取消它，
    可以这么做.</p>
<pre class="python">
from twisted.internet import reactor

def f():
    print "I'll never run."

callID = reactor.callLater(5, f)
callID.cancel()
reactor.run()
</pre>     

    <p>最后要记住所有基于 reactor 的代码，必须先运行<code class="python">
    reactor.run()</code>才可以正常运行.</p>
  </body>
</html>

